"use strict";
const path = require("path");
const defaultSettings = require("./src/settings.js");

function resolve(dir) {
  return path.join(__dirname, dir);
}

const name = defaultSettings.title || "花卉百科"; // page title

// If your port is set to 80,
// use administrator privileges to execute the command line.
// For example, Mac: sudo npm run
// You can change the port by the following methods:
// port = 9528 npm run dev OR npm run dev --port = 9528
const port = process.env.port || process.env.npm_config_port || 8000; // dev port

// All configuration item explanations can be find in https://cli.vuejs.org/config/
module.exports = {
  /**
   * You will need to set publicPath if you plan to deploy your site under a sub path,
   * for example GitHub Pages. If you plan to deploy your site to https://foo.github.io/bar/,
   * then publicPath should be set to "/bar/".
   * In most cases please use '/' !!!
   * Detail: https://cli.vuejs.org/config/#publicpath
   */
  publicPath: "./",
  outputDir: "dist",
  assetsDir: "static",
  lintOnSave: process.env.NODE_ENV === "development",
  productionSourceMap: false,
  devServer: {
    port: port,
    open: true,
    // 代理配置
    proxy: {
      "/api": {
        target: process.env.VUE_APP_BASE_API,
        ws: true,
        changeOrigin: true,
        // logLevel: "debug",
        pathRewrite: { "^/api": "" },
        onProxyReq: function (proxyReq, req, res, options) {
          // 由于vue中使用了body-parser
          // 导致http中的body被序列化两次，从而使得配置代理后后端无法获取body中的数据
          // 感谢https://blog.csdn.net/yuse6262/article/details/107393394提供的解决方案
          if (req.body) {
            const reg = new RegExp("application/json");
            if (reg.test(proxyReq.getHeader("Content-Type"))) {
              const bodyData = JSON.stringify(req.body);
              proxyReq.setHeader("Content-Length", Buffer.byteLength(bodyData));
              // stream the content
              proxyReq.write(bodyData);
            }
          }
        }
      }
    },
    client: {
      overlay: false
    }
  },
  configureWebpack: {
    // provide the app's title in webpack's name field, so that
    // it can be accessed in index.html to inject the correct title.
    name: name,
    resolve: {
      alias: {
        "@": resolve("src")
      }
    }
  }
};
